<?php
declare (strict_types = 1);
/**
 * 素材模型
 */
namespace app\common\model;

class PgmGroupDetail extends BaseModel
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 't_pgmgrp_detail';

    public function matInfoHasOne()
    {
        return $this->hasOne(Material::class, 'mat_id', 'mat_id');
    }

    public function detailLists($where = [], $ordername='seq', $order= 'asc') {

        $whereMat = [];
        $field = '*';

        $list = self::with([
            'matInfoHasOne' => function ($query) use ($whereMat) {
                $query->withField(['mat_id','mat_name', 'file_name', 'file_len', 'markin', 'markout'])->hidden(['mat_id'])->where($whereMat);
            }
        ])->field($field)->where($where)->order([$ordername => $order])->select()->toArray();

        foreach($list as $k =>$v) {
            if($v['matInfoHasOne'] != null) {
                $list[$k] = array_merge($v['matInfoHasOne'], $list[$k]);                               
            }
            unset($list[$k]['matInfoHasOne']);
        }

        foreach($list as $c => $x) {
            $list[$c]['pgm_len'] = ($x['markout'] - $x['markin'] > 0) 
            ? intval($x['markout'] - $x['markin'])  
            : intval($x['file_len'] - $x['markin']);
        }

        return [
            'list' => $list,
            'total' => count($list)
        ];
    }

    // 获取节目组实际长度
    public function pgmgrp_len($where)
    {
        $sum = 0;
        if(!empty($where)) {
            $matlists = self::detailLists($where);
            foreach($matlists['list'] as $c => $x) {
                $sum += ($x['markout'] - $x['markin'] > 0) 
                ? intval($x['markout'] - $x['markin']) 
                : intval($x['file_len'] - $x['markin']);
            }
        }
        return $sum;
    }
}
